﻿Imports System.Data
Imports System.Data.SqlClient

Public Class SqlFeaturesRepository
    Implements IFeaturesRepository

    Private m_connectionString As String

    Public Sub New(connectionString As String)
        m_connectionString = connectionString
    End Sub

    Public Function LoadFeatures() As Dictionary(Of String, Boolean) Implements IFeaturesRepository.LoadFeatures
        Dim features As New Dictionary(Of String, Boolean)

        Using connection As New SqlConnection(m_connectionString)
            Try
                connection.Open()
                Dim cmd = connection.CreateCommand()
                cmd.CommandText = "LoadFeatures"
                cmd.CommandType = CommandType.StoredProcedure
                Dim featuresReader = cmd.ExecuteReader()
                While featuresReader.Read()
                    features.Add(featuresReader(0).ToString(), Boolean.Parse(featuresReader(1).ToString()))
                End While
                featuresReader.Close()
            Catch ex As Exception
                Throw
            End Try
        End Using
        Return features
    End Function

    Public Sub SaveFeaturesState(features As Dictionary(Of String, Boolean)) Implements IFeaturesRepository.SaveFeatures
        For Each f In features.Keys
            InsertOrUpdateFeature(f, features(f))
        Next
    End Sub

    Private Sub InsertOrUpdateFeature(feature As String, isEnabled As Boolean)
        Using connection As New SqlConnection(m_connectionString)
            Try
                connection.Open()
                Dim cmd = connection.CreateCommand()
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "InsertOrUpdateFeatures"
                cmd.Parameters.AddWithValue("@fullTypeName", feature)
                cmd.Parameters.AddWithValue("@isEnabled", isEnabled)
                cmd.ExecuteNonQuery()
            Catch ex As Exception
                Throw
            End Try
        End Using
    End Sub

End Class
